package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 子工程信息表Controller
 * 
 * @author SYGIS
 * @date 2023-09-13
 */
@RestController
@RequestMapping("/system/subengineer")
public class SySubEngineerController extends BaseController {

    @Autowired
    private ISySubEngineerService sySubEngineerService;

    @Autowired
    private ISyEngineerService engineerService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISyProjectService projectService;

    @Autowired
    private ISyFileInfoService fileInfoService;

    @Autowired
    private ISyDatasetInfoService datasetInfoService;

    @PostMapping("/createSubEngineerNo")
    public AjaxResult createSubEngineerNo(){
        SimpleDateFormat format = new SimpleDateFormat("YYYYMMddHHmmssSSS");
        String subEngineerNo = "YNJT-SUBENGINEER-"+format.format(new Date());
        Map<Object,Object> res = new HashMap<>();
        res.put("subEngineerNo",subEngineerNo);
        return AjaxResult.success(res);
    }

    @PostMapping("/unhookSubEngineer")
    public AjaxResult unhookSubEngineer(@RequestBody SySubEngineer sySubEngineer) {
        sySubEngineerService.releaseSubEngineerByUuid(sySubEngineer.getUuid());
        return AjaxResult.success();
    }

    @PostMapping("/editSubEngineer")
    public AjaxResult editSubEngineer(@RequestBody SySubEngineer sySubEngineer) {
        if(sySubEngineer.getUuid()==null){ //新增
            sySubEngineer.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
            sySubEngineer.setCreateBy(SecurityUtils.getLoginUser().getUserId().toString());
            sySubEngineer.setCreateTime(new Date());
            sySubEngineer.setStatus(1);
            sySubEngineerService.insertSySubEngineer(sySubEngineer);
        }else{ //修改
            sySubEngineer.setUpdateBy(SecurityUtils.getLoginUser().getUserId().toString());
            sySubEngineer.setUpdateTime(new Date());
            sySubEngineerService.updateSySubEngineer(sySubEngineer);
        }
        return AjaxResult.success();
    }

    @GetMapping("/getSubEngineer4ProjectDetail")
    public AjaxResult getSubEngineer4ProjectDetail(SySubEngineer sySubEngineer) {
        List<SySubEngineer> list = sySubEngineerService.selectSySubEngineerList(sySubEngineer);
        if(list.size()>0){
            for(SySubEngineer subEngineer:list){
                if(subEngineer.getProjectId()!=null){
                    SyProject project = projectService.selectSyProjectByUuid(subEngineer.getProjectId());
                    if(project!=null){
                        subEngineer.setProjectName(project.getName());
                    }
                }
                if(subEngineer.getEngineerId()!=null){
                    SyEngineer engineer = engineerService.selectSyEngineerByUuid(subEngineer.getEngineerId());
                    if(engineer!=null){
                        subEngineer.setEngineerName(engineer.getName());
                    }
                }
            }
        }
        return AjaxResult.success(list);
    }

    @GetMapping("/getSubEngineerList4Engineer")
    public AjaxResult getSubEngineerList4Engineer(SySubEngineer sySubEngineer) {
        List<SySubEngineer> list = sySubEngineerService.selectSubEngineerList4Engineer(sySubEngineer);
        if(list.size()>0){
            for(SySubEngineer subEngineer:list){
                if(subEngineer.getEngineerId()!=null){
                    subEngineer.setHasEngineer(1);
                }else{
                    subEngineer.setHasEngineer(0);
                }
                if(subEngineer.getProjectId()!=null){
                    SyProject project = projectService.selectSyProjectByUuid(subEngineer.getProjectId());
                    if(project!=null){
                        subEngineer.setProjectName(project.getName());
                    }
                }
                if(subEngineer.getEngineerId()!=null){
                    SyEngineer engineer = engineerService.selectSyEngineerByUuid(subEngineer.getEngineerId());
                    if(engineer!=null){
                        subEngineer.setEngineerName(engineer.getName());
                    }
                }
            }
        }
        return AjaxResult.success(list);
    }

    /**
     * 查询子工程信息表列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SySubEngineer sySubEngineer) {
        startPage();
        List<SySubEngineer> list = sySubEngineerService.selectSySubEngineerList(sySubEngineer);
        if(list.size()>0){
            for(SySubEngineer subEngineer:list){
                if(subEngineer.getChargerId()!=null){
                    SysUser user = userService.selectUserById(subEngineer.getChargerId());
                    if(user!=null){
                        subEngineer.setChargerName(user.getNickName());
                    }
                }
                if(subEngineer.getDeptId()!=null){
                    SysDept dept = deptService.selectDeptById(subEngineer.getDeptId());
                    if(dept!=null){
                        subEngineer.setDeptName(dept.getDeptName());
                    }
                }
                if(subEngineer.getProjectId()!=null){
                    SyProject project = projectService.selectSyProjectByUuid(subEngineer.getProjectId());
                    if(project!=null){
                        subEngineer.setProjectName(project.getName());
                    }
                }
                if(subEngineer.getEngineerId()!=null){
                    SyEngineer engineer = engineerService.selectSyEngineerByUuid(subEngineer.getEngineerId());
                    if(engineer!=null){
                        subEngineer.setEngineerName(engineer.getName());
                    }
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出子工程信息表列表
     */
    @Log(title = "子工程信息表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SySubEngineer sySubEngineer) {
        List<SySubEngineer> list = sySubEngineerService.selectSySubEngineerList(sySubEngineer);
        ExcelUtil<SySubEngineer> util = new ExcelUtil<SySubEngineer>(SySubEngineer.class);
        util.exportExcel(response, list, "子工程信息表数据");
    }

    /**
     * 获取子工程信息表详细信息
     */
    @GetMapping(value = "/{uuid}")
    public AjaxResult getInfo(@PathVariable("uuid") String uuid) {
        SySubEngineer subEngineer = sySubEngineerService.selectSySubEngineerByUuid(uuid);
        if(subEngineer!=null){
            if(subEngineer.getMaterialAttach()!=null){
                List<SyFileInfo> attachList = getAttachList(subEngineer.getMaterialAttach());
                subEngineer.setAttachList(attachList);
            }
            if(subEngineer.getChargerId()!=null){
                SysUser user = userService.selectUserById(subEngineer.getChargerId());
                if(user!=null){
                    subEngineer.setChargerName(user.getNickName());
                }
            }
            if(subEngineer.getDeptId()!=null){
                SysDept dept = deptService.selectDeptById(subEngineer.getDeptId());
                if(dept!=null){
                    subEngineer.setDeptName(dept.getDeptName());
                }
            }
            if(subEngineer.getCreateBy()!=null){
                SysUser user = userService.selectUserById(Long.parseLong(subEngineer.getCreateBy()));
                if(user!=null){
                    subEngineer.setCreator(user.getNickName());
                }
            }
            if(subEngineer.getProjectId()!=null){
                SyProject project = projectService.selectSyProjectByUuid(subEngineer.getProjectId());
                if(project!=null){
                    subEngineer.setProjectName(project.getName());
                }
            }
            if(subEngineer.getEngineerId()!=null){
                SyEngineer engineer = engineerService.selectSyEngineerByUuid(subEngineer.getEngineerId());
                if(engineer!=null){
                    subEngineer.setEngineerName(engineer.getName());
                }
            }
        }
        return success(subEngineer);
    }

    public List<SyFileInfo> getAttachList(String attachUrl){
        String[] attachArray = null;
        if(attachUrl!=null){
            String url = attachUrl.replaceAll(" ","");
            if(url.length()>0){
                attachArray = attachUrl.split(",");
            }
        }
        List<SyFileInfo> list = new ArrayList<>();
        if(attachArray!=null){
            if(attachArray.length>0){
                for(String url:attachArray){
                    SyFileInfo fileInfo = new SyFileInfo();
                    fileInfo.setUrl(url);
                    List<SyFileInfo> files = fileInfoService.selectSyFileInfoList(fileInfo);
                    SyFileInfo file = files.get(0);
                    if(file!=null){
                        file.setName(file.getOriginName());
                    }
                    list.add(file);
                }
            }
        }
        return list;
    }

    /**
     * 新增子工程信息表
     */
    @Log(title = "子工程信息表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SySubEngineer sySubEngineer) {
        return toAjax(sySubEngineerService.insertSySubEngineer(sySubEngineer));
    }

    /**
     * 修改子工程信息表
     */
    @Log(title = "子工程信息表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SySubEngineer sySubEngineer) {
        return toAjax(sySubEngineerService.updateSySubEngineer(sySubEngineer));
    }

    /**
     * 删除子工程信息表
     */
    @Log(title = "子工程信息表", businessType = BusinessType.DELETE)
	@DeleteMapping("/{uuids}")
    public AjaxResult remove(@PathVariable String[] uuids) {
        return toAjax(sySubEngineerService.deleteSySubEngineerByUuids(uuids));
    }

    @PostMapping("/processStartSubEngineer")
    public AjaxResult processStartSubEngineer(@RequestBody SySubEngineer sySubEngineer) {
        SySubEngineer subEngineer = sySubEngineerService.selectSySubEngineerByUuid(sySubEngineer.getUuid());
        if(subEngineer!=null){
            subEngineer.setStatus(2);
            sySubEngineerService.updateSySubEngineer(subEngineer);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的子工程信息");
        }
    }

    @PostMapping("/processDeleteSubEngineer")
    public AjaxResult processDeleteSubEngineer(@RequestBody SySubEngineer sySubEngineer) {
        SySubEngineer subEngineer = sySubEngineerService.selectSySubEngineerByUuid(sySubEngineer.getUuid());
        if(subEngineer!=null){
            sySubEngineerService.deleteSySubEngineerByUuid(subEngineer.getUuid());
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的子工程信息");
        }
    }

    @PostMapping("/processRestartSubEngineer")
    public AjaxResult processRestartSubEngineer(@RequestBody SySubEngineer sySubEngineer) {
        SySubEngineer subEngineer = sySubEngineerService.selectSySubEngineerByUuid(sySubEngineer.getUuid());
        if(subEngineer!=null){
            subEngineer.setStatus(2);
            sySubEngineerService.updateSySubEngineer(subEngineer);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的子工程信息");
        }
    }

    @PostMapping("/processFinishSubEngineer")
    public AjaxResult processFinishSubEngineer(@RequestBody SySubEngineer sySubEngineer) {
        SySubEngineer subEngineer = sySubEngineerService.selectSySubEngineerByUuid(sySubEngineer.getUuid());
        if(subEngineer!=null){
            subEngineer.setStatus(3);
            sySubEngineerService.updateSySubEngineer(subEngineer);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的子工程信息");
        }
    }

    @PostMapping("/processNullifySubEngineer")
    public AjaxResult processNullifySubEngineer(@RequestBody SySubEngineer sySubEngineer) {
        SySubEngineer subEngineer = sySubEngineerService.selectSySubEngineerByUuid(sySubEngineer.getUuid());
        if(subEngineer!=null){
            subEngineer.setStatus(4);
            sySubEngineerService.updateSySubEngineer(subEngineer);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的子工程信息");
        }
    }

    @PostMapping("/processInitSubEngineer")
    public AjaxResult processInitSubEngineer(@RequestBody SySubEngineer sySubEngineer) {
        SySubEngineer subEngineer = sySubEngineerService.selectSySubEngineerByUuid(sySubEngineer.getUuid());
        if(subEngineer!=null){
            subEngineer.setStatus(1);
            sySubEngineerService.updateSySubEngineer(subEngineer);
            return AjaxResult.success();
        }else{
            return AjaxResult.error("没有找到对应的子工程信息");
        }
    }

    @GetMapping("/getRoleSubEngineerList")
    public AjaxResult getRoleSubEngineerList(SySubEngineer param) {
        List<SySubEngineer> list = new ArrayList<>();
        List<SySubEngineer> unbindRoleList = sySubEngineerService.selectUnbindRoleList(param.getRoleIds());
        List<SySubEngineer> bindRoleList = sySubEngineerService.selectBindRoleList(param.getRoleIds());
        if(unbindRoleList.size()>0){
            for (SySubEngineer res:unbindRoleList){
                res.setHasRole(0);
                list.add(res);
            }
        }
        if(bindRoleList.size()>0){
            for (SySubEngineer res:bindRoleList){
                res.setHasRole(1);
                list.add(res);
            }
        }
        return AjaxResult.success(list);
    }

    @PostMapping("/saveRoleSubEngineer")
    public AjaxResult saveRoleSubEngineer(@RequestBody SySubEngineer param){
        String[] ids = param.getIds().split(",");
        if(ids.length>0) {
            for (String id : ids) {
                SySubEngineer subEngineer = sySubEngineerService.selectSySubEngineerByUuid(id);
                if(subEngineer!=null){
                    if(subEngineer.getRoleIds()!=null){
                        if(subEngineer.getRoleIds().indexOf(param.getRoleIds())<0){
                            subEngineer.setRoleIds(subEngineer.getRoleIds()+","+param.getRoleIds());
                        }
                    }else{
                        subEngineer.setRoleIds(param.getRoleIds());
                    }
                    sySubEngineerService.updateSySubEngineer(subEngineer);
                }
            }
        }
        return AjaxResult.success();
    }

    @PostMapping("/unhookRoleSubEngineer")
    public AjaxResult unhookRoleSubEngineer(@RequestBody SySubEngineer param) {
        SySubEngineer subEngineer = sySubEngineerService.selectSySubEngineerByUuid(param.getUuid());
        if(subEngineer!=null){
            if(subEngineer.getRoleIds()!=null){
                String roleIds = subEngineer.getRoleIds().replaceAll(","+param.getRoleIds(),"").replaceAll(param.getRoleIds(),"");
                subEngineer.setRoleIds(roleIds);
                sySubEngineerService.updateSySubEngineer(subEngineer);
            }
        }
        return AjaxResult.success();
    }

    @GetMapping("/getBindRoleSubEngineerList")
    public AjaxResult getBindRoleSubEngineerList(SySubEngineer param) {
        List<SySubEngineer> list = new ArrayList<>();
        List<SySubEngineer> bindRoleList = sySubEngineerService.selectBindRoleList(param.getRoleIds());
        if(bindRoleList.size()>0){
            for (SySubEngineer res:bindRoleList){
                res.setHasRole(1);
                list.add(res);
            }
        }
        return AjaxResult.success(list);
    }

    @GetMapping("/getDatasetSubEngineerList")
    public AjaxResult getDatasetSubEngineerList(SySubEngineer param) {
        List<SySubEngineer> list = sySubEngineerService.selectDatasetSubEngineerList();
        if(list.size()>0){
            for(SySubEngineer subEngineer:list){
                List<SyDatasetInfo> datasets = datasetInfoService.selectDatasetByUuidAndSubEngineerId(param.getUuid(),subEngineer.getUuid());
                if(datasets.size()>0){
                    subEngineer.setHasRole(1);
                }else{
                    subEngineer.setHasRole(0);
                }
            }
        }
        return AjaxResult.success(list);
    }

    @PostMapping("/saveDatasetSubEngineer")
    public AjaxResult saveDatasetSubEngineer(@RequestBody SySubEngineer param){
        SyDatasetInfo dataset = datasetInfoService.selectSyDatasetInfoByUuid(param.getUuid());
        if(dataset!=null){
            if(dataset.getSubEngineerIds()!=null){
                String[] ids = param.getIds().split(",");
                if(ids.length>0) {
                    for (String id : ids) {
                        if(dataset.getSubEngineerIds().indexOf(id)<0){
                            dataset.setSubEngineerIds(dataset.getSubEngineerIds()+","+id);
                        }
                    }
                }
            }else{
                dataset.setSubEngineerIds(param.getIds());
            }
        }
        datasetInfoService.updateSyDatasetInfo(dataset);
        return AjaxResult.success();
    }

    @PostMapping("/unhookDatasetSubEngineer")
    public AjaxResult unhookDatasetSubEngineer(@RequestBody SySubEngineer param){
        SyDatasetInfo dataset = datasetInfoService.selectSyDatasetInfoByUuid(param.getUuid());
        if(dataset!=null){
            String subEngineerIds = dataset.getSubEngineerIds().replaceAll(","+param.getIds(),"").replaceAll(param.getIds(),"");
            dataset.setSubEngineerIds(subEngineerIds);
            datasetInfoService.updateSyDatasetInfo(dataset);
        }
        return AjaxResult.success();
    }

    @GetMapping("/getBindDatasetSubEngineerList")
    public AjaxResult getBindDatasetSubEngineerList(SySubEngineer param) {
        SyDatasetInfo dataset = datasetInfoService.selectSyDatasetInfoByUuid(param.getUuid());
        List<SySubEngineer> list = new ArrayList<>();
        if(dataset!=null){
            if(dataset.getSubEngineerIds()!=null){
                if(dataset.getSubEngineerIds().length()>0){
                    String[] ids = dataset.getSubEngineerIds().split(",");
                    if(ids.length>0) {
                        for (String id : ids) {
                            if(id.replaceAll(" ","").length()>0){
                                SySubEngineer subEngineer = sySubEngineerService.selectSySubEngineerByUuid(id);
                                if(subEngineer!=null){
                                    subEngineer.setHasRole(1);
                                    list.add(subEngineer);
                                }
                            }
                        }
                    }
                }
            }
        }
        return AjaxResult.success(list);
    }
}
